package zju.lzy.service.message;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import zju.lzy.dto.IOTMessage;
import zju.lzy.dto.MessageReq;
import zju.lzy.mapper.MessageMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

@Component
public class MessageService {

    private static final Logger logger = LoggerFactory.getLogger(MessageService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private MessageReceiver messageReceiver;

    public List<IOTMessage> queryMessages(MessageReq messageReq) {

        List<IOTMessage> permList = jdbcTemplate.query(messageReq.generateSql(), new RowMapper<IOTMessage>() {
            @Override
            public IOTMessage mapRow(ResultSet resultSet, int i) throws SQLException {
                IOTMessage msg = new IOTMessage();
                msg.setSender(resultSet.getInt("sender"));
                msg.setTopic(resultSet.getString("topic"));
                msg.setClientId(resultSet.getString("clientId"));
                msg.setInfo(resultSet.getString("info"));
                msg.setValue(resultSet.getInt("value"));
                msg.setAlert(resultSet.getInt("alert"));
                msg.setLat(resultSet.getDouble("lat"));
                msg.setLon(resultSet.getDouble("lon"));
                msg.setTimestamp(resultSet.getLong("timestamp"));
                return msg;
            }
        });
        List<IOTMessage> cacheList = messageReceiver.queryCachedMessages(messageReq);
        permList.addAll(cacheList);
        return permList;
    }

    public List<IOTMessage> getDataBySender(Integer sender) {
        List<IOTMessage> permList = messageMapper.getDataBySender(sender);
        permList.addAll(
                messageReceiver.getDataBySender(sender)
        );
        return permList;
    }

}
